import 'package:bili_caricature/base/base_state.dart';
import 'package:bili_caricature/models/handle_state.dart';
import 'package:bloc/bloc.dart';
import '../../../models/response_model.dart';
import '../../../net/http_config.dart';
import '../../../net/ltt_https.dart';
import '../../../widgets/easy_loading.dart';
import '../model/info_model.dart';
import 'state.dart';

class MessageModuleCubit extends Cubit<MessageModuleState> {
  MessageModuleCubit() : super(MessageModuleState().init());

  /// 获取数据
  Future<void> getListData(String path, int pageNum) async {
    /// 复制一个新的对象
    var nerStates = state.clone();
    XsEasyLoading.showLoading();
    ResponseModel? responseModel = await LttHttp().request<InfoListModel>(path,
        params: {"pn": pageNum, "ps": 20, "q": "车讯原创", "t": 0}, method: HttpConfig.get);
    XsEasyLoading.dismiss();

    /// 根据数据更新页面状态
    nerStates.netState = HandleState.handle(responseModel, nerStates);
    if (nerStates.netState == NetState.dataSuccessState) {
      InfoListModel infoListModel = responseModel.data;
      nerStates.netLoadCount += 1;
      if (pageNum == 1) {
        nerStates.dataList = infoListModel.works;
        if ((state.dataList ?? []).isEmpty) {
          state.netState = NetState.emptyDataState;
        }
      } else {
        nerStates.dataList?.addAll(infoListModel.works);
        if (infoListModel.works.isEmpty) {
          nerStates.isNoMoreDataState = true;
        }
      }
    }
    emit(nerStates);
  }
}
